from django.db import models
from django.core.exceptions import ValidationError
from common.models.system import Dictionary, Users
from utils.models import CoreModel, SoftDeleteModel, DeptBelongModel


# 项目模型类
class ProjectInfo(CoreModel, SoftDeleteModel, DeptBelongModel):
    name = models.CharField(max_length=255, verbose_name='项目名称')
    project_no = models.CharField(max_length=255, null=True, blank=True, verbose_name='商机编号')
    dept = models.ForeignKey('Dept', on_delete=models.DO_NOTHING, db_constraint=False, verbose_name='所属区划')
    price = models.FloatField(verbose_name='商机规模', help_text='单位 万元')
    lead_company = models.CharField(max_length=2, verbose_name='项目主导方')
    competitions = models.CharField(max_length=255, verbose_name='主要竞争对手')
    # 预留字段
    important_level = models.CharField(max_length=2, null=True, verbose_name='重要性')
    priority_level = models.CharField(max_length=2, null=False, default=1, verbose_name='项目类型')
    status = models.CharField(max_length=2, default='1', verbose_name='状态')

    jf_relationship = models.CharField(max_length=2, null=True, blank=True, verbose_name='甲方客情关系程度')
    jf_name = models.CharField(max_length=255, null=True, blank=True, verbose_name='甲方单位名称')
    jf_manager_name = models.CharField(max_length=255, null=True, blank=True, verbose_name='甲方关键人姓名')
    jf_manager_job = models.CharField(max_length=255, null=True, blank=True, verbose_name='甲方关键人职位')
    gys_relationship = models.CharField(max_length=2, null=True, blank=True, verbose_name='供应商客情关系程度')
    gys_name = models.CharField(max_length=255, null=True, blank=True, verbose_name='供应商单位名称')
    gys_manager_name = models.CharField(max_length=255, null=True, blank=True, verbose_name='供应商关键人姓名')
    gys_manager_job = models.CharField(max_length=255, null=True, blank=True, verbose_name='供应商关键人职位')
    zbdl_relationship = models.CharField(max_length=2, null=True, blank=True, verbose_name='招标代理客情关系程度')
    zbdl_name = models.CharField(max_length=255, null=True, blank=True, verbose_name='招标代理单位名称')
    zbdl_manager_name = models.CharField(max_length=255, null=True, blank=True, verbose_name='招标代理关键人姓名')
    zbdl_manager_job = models.CharField(max_length=255, null=True, blank=True, verbose_name='招标代理关键人职位')
    zj_relationship = models.CharField(max_length=2, null=True, blank=True, verbose_name='专家客情关系程度')
    zj_name = models.CharField(max_length=255, null=True, blank=True, verbose_name='招标代理单位名称')
    kq_plan = models.CharField(max_length=2000, null=True, blank=True, verbose_name='整体客情分析与下一步规划')

    get_date = models.DateField(null=True, verbose_name='商机获取日期')
    save_date = models.DateField(null=True, verbose_name='商机录入日期')
    get_compare = models.CharField(max_length=2, null=True, blank=True, verbose_name='商机获取与竞对比较')
    lead_compare = models.CharField(max_length=1000, null=True, blank=True, verbose_name='主导关系比对')
    scheme_compare = models.CharField(max_length=1000, null=True, blank=True, verbose_name='方案能力比对')
    price_compare = models.CharField(max_length=1000, null=True, blank=True, verbose_name='报价策略比对')
    compare_plan = models.CharField(max_length=2000, null=True, blank=True, verbose_name='整体竞对比较与下一步规划')

    sjgjqyjd = models.BooleanField(null=True, verbose_name='商机跟进是否强于竞对')
    kqgxsfjrkb = models.BooleanField(null=True, verbose_name='客情关系是否介入控标')
    fanlsfjbjzl = models.BooleanField(null=True, verbose_name='方案能力是否具备竞争力')
    summarize = models.CharField(max_length=2000, null=True, blank=True, verbose_name='情况总结')
    next_plan = models.CharField(max_length=2000, null=True, blank=True, verbose_name='下一步攻坚规划')

    class Meta:
        managed = False
        db_table = 'project_info'
        verbose_name = '项目信息表'
        verbose_name_plural = verbose_name
        ordering = ('-create_time',)


class ProjectInfoUpdateLog(CoreModel, SoftDeleteModel):
    project = models.ForeignKey('ProjectInfo', on_delete=models.DO_NOTHING, verbose_name='项目id')
    before = models.JSONField(verbose_name='修改前')
    after = models.JSONField(verbose_name='修改后')

    class Meta:
        managed = False
        db_table = 'project_info_update_log'
        verbose_name = '项目信息更新记录表'
        verbose_name_plural = verbose_name
        ordering = ('-create_time',)


class ProjectWarn(CoreModel, SoftDeleteModel):
    project = models.ForeignKey('ProjectInfo', on_delete=models.DO_NOTHING, verbose_name='项目id')
    content = models.CharField(max_length=255, verbose_name='预警内容')
    type = models.CharField(max_length=2, verbose_name='预警类型', help_text='1长时间未更新')
    read_status = models.CharField(max_length=2, default='0', verbose_name='已读状态')
    is_handled = models.BooleanField(default=False, verbose_name='是否消警')

    class Meta:
        managed = False
        db_table = 'project_warn'
        verbose_name = '预警记录表'
        verbose_name_plural = verbose_name
        ordering = ('-create_time',)


class GroupCustomerInfo(CoreModel, SoftDeleteModel, DeptBelongModel):
    group_id = models.CharField(max_length=50, blank=True, verbose_name='集团编号')
    group_name = models.CharField(max_length=200, verbose_name='集团名称')
    dept = models.ForeignKey('Dept', on_delete=models.DO_NOTHING, db_constraint=False, verbose_name='所属区划')
    industry_category = models.CharField(max_length=100, blank=True, null=True, verbose_name='行业类别')
    group_status = models.CharField(max_length=50, blank=True, null=True, verbose_name='集团状态')
    group_actual_level = models.CharField(max_length=50, blank=True, null=True, verbose_name='集团实际级别')
    group_address = models.TextField(blank=True, null=True, verbose_name='集团地址')
    # account_manager_user_id = models.CharField(max_length=50, blank=True, null=True, verbose_name='客户经理对应的用户 ID')
    network_user_count = models.IntegerField(blank=True, null=True, verbose_name='本网人数')
    is_strategic_customer = models.BooleanField(null=True, verbose_name='是否为战略客户')
    is_value_customer = models.BooleanField(null=True, verbose_name='是否为价值客户')
    group_decision_maker = models.CharField(max_length=255, blank=True, null=False, verbose_name='集团决策人')
    group_contact_person = models.CharField(max_length=255, blank=True, null=False, verbose_name='集团联系人')
    chief_account_manager = models.CharField(max_length=255, blank=True, null=True, verbose_name='首席客户经理')
    employee_user_count = models.IntegerField(default=0, verbose_name='员工用户数')
    remark = models.TextField(blank=True, null=True, verbose_name='备注字段')

    class Meta:
        managed = False
        db_table = 'group_customer_info'
        verbose_name = '集团客户信息表'
        verbose_name_plural = verbose_name
        ordering = ('-create_time',)


class GroupInformationStatistics(CoreModel, SoftDeleteModel, DeptBelongModel):
    # 关联集团，修改为 OneToOneField
    group = models.OneToOneField(
        'GroupCustomerInfo',
        on_delete=models.SET_NULL,
        null=True,
        blank=True,
        related_name='statistics',
        verbose_name='关联集团'
    )
    # ---手机用户相关
    # 我网用户数
    our_net_user_cnt = models.IntegerField(default=0, verbose_name='我网用户数')
    # 线盒渗透数
    wiring_box_cnt = models.IntegerField(default=0, verbose_name='线盒渗透数')
    # 合户及代付用户数
    joint_pay_user_cnt = models.IntegerField(default=0, verbose_name='合户及代付用户数')
    # 集团合约及赠 5G 金币用户数
    group_5g_coin_user_cnt = models.IntegerField(default=0, verbose_name='集团合约及赠5G金币用户数')
    # LT 用户数
    lt_user_cnt = models.IntegerField(default=0, verbose_name='LT用户数')
    # LT 合约及赠机用户数
    lt_contract_gift_user_cnt = models.IntegerField(default=0, verbose_name='LT合约及赠机用户数')
    # DX 用户数
    dx_user_cnt = models.IntegerField(default=0, verbose_name='DX用户数')
    # DX 合约及赠机用户数
    dx_contract_gift_user_cnt = models.IntegerField(default=0, verbose_name='DX合约及赠机用户数')

    # ---专线相关
    # 是否竞对集团（是/否）
    is_competing = models.BooleanField(null=True, verbose_name='是否竞对集团')
    # 数据专线条数（条）
    data_line_cnt = models.IntegerField(default=0, verbose_name='数据专线条数')
    # 数据专线合计月收入（元）
    data_line_income = models.DecimalField(max_digits=10, decimal_places=2, default=0,
                                           verbose_name='数据专线合计月收入')
    # 互联网专线条数（条）
    internet_line_cnt = models.IntegerField(default=0, verbose_name='互联网专线条数')
    # 互联网专线合计月收入（元）
    internet_line_income = models.DecimalField(max_digits=10, decimal_places=2, default=0,
                                               verbose_name='互联网专线合计月收入')
    # LT 数据专线条数（xx条）
    lt_data_line_cnt = models.IntegerField(default=0, verbose_name='LT数据专线条数')
    # LT 互联网专线条数（条）
    lt_internet_line_cnt = models.IntegerField(default=0, verbose_name='LT互联网专线条数')
    # DX 数据专线条数（xx条）
    dx_data_line_cnt = models.IntegerField(default=0, verbose_name='DX数据专线条数')
    # DX 互联网专线条数（条）
    dx_internet_line_cnt = models.IntegerField(default=0, verbose_name='DX互联网专线条数')
    # GD 数据专线条数（xx条）
    gd_data_line_cnt = models.IntegerField(default=0, verbose_name='GD数据专线条数')
    # GD 互联网专线条数（条）
    gd_internet_line_cnt = models.IntegerField(default=0, verbose_name='GD互联网专线条数')
    # 异网专线合计月收入（元）
    other_net_income = models.DecimalField(max_digits=10, decimal_places=2, default=0,
                                           verbose_name='异网专线合计月收入')
    # 存量数据专线条数（我网、异网合计）
    stock_data_line_cnt = models.IntegerField(default=0, verbose_name='存量数据专线条数')
    # 存量互联网专线条数（我网、异网合计）
    stock_internet_line_cnt = models.IntegerField(default=0, verbose_name='存量互联网专线条数')

    # 备注字段
    remark = models.TextField(blank=True, null=True, verbose_name='备注字段')

    class Meta:
        managed = False
        db_table = 'group_information_statistics'
        verbose_name = '集团信息统计表'
        verbose_name_plural = verbose_name
        ordering = ('-update_time',)

    def __str__(self):
        return f"{self.group.group_name if self.group else 'No Group'} - {self.statistics_date}"


class MobileUserRecord(CoreModel, SoftDeleteModel, DeptBelongModel):
    # 关联到 GroupCustomerInfo 模型的外键字段
    group = models.ForeignKey(GroupCustomerInfo, on_delete=models.DO_NOTHING, verbose_name='关联集团')
    # 我网用户数，整数字段
    our_net_users = models.IntegerField(default=0, verbose_name='我网用户（户）')
    # 线盒渗透情况，字符串字段，最大长度 255
    wiring_box_penetration = models.IntegerField(default=0, verbose_name='线盒渗透')
    # 合户及代付用户数，整数字段
    joint_pay_users = models.IntegerField(default=0, verbose_name='合户及代付用户数（户）')
    # 我网集团合约及赠 5G 金币用户数，整数字段
    our_net_5g_coin_users = models.IntegerField(default=0, verbose_name='我网集团合约及赠5G金币用户（户）')
    # 集团合约及 5G 金币到期日期，字符串字段，最大长度 20
    group_5g_coin_exp_date = models.DateField(null=True, verbose_name='集团合约及5G金币到期日期')
    group_5g_coin_is_exp = models.BooleanField(default=True, verbose_name='定时任务是否处理标记')
    # LT 用户数，整数字段
    lt_users = models.IntegerField(default=0, verbose_name='LT用户（户）')
    # LT 合约及赠机用户数，整数字段
    lt_contract_gift_users = models.IntegerField(default=0, verbose_name='LT合约及赠机用户（户）')
    # LT 到期日期，字符串字段，最大长度 20
    lt_exp_date = models.DateField(null=True, verbose_name='LT到期日期')
    lt_is_exp = models.BooleanField(default=True, verbose_name='LT是否到期')
    # DX 用户数，整数字段
    dx_users = models.IntegerField(default=0, verbose_name='DX用户（户）')
    # DX 合约及赠机用户数，整数字段
    dx_contract_gift_users = models.IntegerField(default=0, verbose_name='DX合约及赠机用户（户）')
    # DX 到期日期，字符串字段，最大长度 20
    dx_exp_date = models.DateField(null=True, verbose_name='DX到期日期')
    dx_is_exp = models.BooleanField(default=True, verbose_name='DX是否到期')
    # 增加数据类型--我网异网
    data_type = models.CharField(max_length=20, blank=True, null=True, verbose_name='数据类型')

    class Meta:
        managed = False
        db_table = 'mobile_user_record'
        verbose_name = '手机用户管理记录表'
        verbose_name_plural = verbose_name
        ordering = ('-update_time',)

    def __str__(self):
        return f"{self.group.group_name if self.group else 'No Group'} - 手机用户记录"


class SpecialLineManagement(CoreModel, SoftDeleteModel, DeptBelongModel):
    # 我网数据专线相关字段
    data_line_count = models.IntegerField(default=0, verbose_name='数据专线条数')
    data_line_income = models.DecimalField(max_digits=10, decimal_places=2, default=0,
                                           verbose_name='数据专线合计月收入')
    data_line_expiry = models.DateField(null=True, verbose_name='数据专线到期日期')
    data_line_is_exp = models.BooleanField(default=True, verbose_name='数据专线到期是否处理')

    # 我网互联网专线相关字段
    internet_line_count = models.IntegerField(default=0, verbose_name='互联网专线条数')
    internet_line_income = models.DecimalField(max_digits=10, decimal_places=2, default=0,
                                               verbose_name='互联网专线合计月收入')
    internet_line_expiry = models.DateField(null=True, verbose_name='互联网专线到期日期')
    internet_line_is_exp = models.BooleanField(
        default=True, verbose_name='互联网专线到期是否处理', help_text='已到期且为False时需要定时任务处理')

    # 我网存量专线合计月收入
    my_network_income = models.DecimalField(max_digits=10, decimal_places=2, default=0,
                                            verbose_name='我网存量专线合计月收入')

    # 联通数据专线情况
    lt_data_count = models.IntegerField(default=0, verbose_name='LT 数据专线条数')
    lt_data_fee = models.DecimalField(max_digits=10, decimal_places=2, default=0, verbose_name='LT 数据专线资费')
    lt_internet_count = models.IntegerField(default=0, verbose_name='LT 互联网专线条数')
    lt_internet_fee = models.DecimalField(max_digits=10, decimal_places=2, default=0,
                                          verbose_name='LT 互联网专线资费')
    lt_expiry = models.DateField(null=True, verbose_name='LT 协议到期时间')
    lt_is_exp = models.BooleanField(default=True, verbose_name='lt到期是否处理')

    # 电信数据专线情况
    dx_data_count = models.IntegerField(default=0, verbose_name='DX 数据专线条数')
    dx_data_fee = models.DecimalField(max_digits=10, decimal_places=2, default=0, verbose_name='DX 数据专线资费')
    dx_internet_count = models.IntegerField(default=0, verbose_name='DX 互联网专线条数')
    dx_internet_fee = models.DecimalField(max_digits=10, decimal_places=2, default=0,
                                          verbose_name='DX 互联网专线资费')
    dx_expiry = models.DateField(null=True, verbose_name='DX 协议到期时间')
    dx_is_exp = models.BooleanField(default=True, verbose_name='dx到期是否处理')

    # 广电数据专线情况
    gd_data_count = models.IntegerField(default=0, verbose_name='GD 数据专线条数')
    gd_data_fee = models.DecimalField(max_digits=10, decimal_places=2, default=0, verbose_name='GD 数据专线资费')
    gd_internet_count = models.IntegerField(default=0, verbose_name='GD 互联网专线条数')
    gd_internet_fee = models.DecimalField(max_digits=10, decimal_places=2, default=0,
                                          verbose_name='GD 互联网专线资费')
    gd_expiry = models.DateField(null=True, verbose_name='GD 协议到期时间')
    gd_is_exp = models.BooleanField(default=True, verbose_name='gd到期是否处理')

    # 增加数据类型--我网异网
    data_type = models.CharField(max_length=20, blank=True, null=True, verbose_name='数据类型')

    # 关联集团
    group = models.ForeignKey('GroupCustomerInfo', on_delete=models.DO_NOTHING, db_constraint=False,
                              verbose_name='关联集团信息')

    class Meta:
        managed = False
        db_table = 'special_line_management'
        verbose_name = '专线管理表'
        verbose_name_plural = verbose_name
        ordering = ('-create_time',)


class InformationPlatformRecord(CoreModel, SoftDeleteModel, DeptBelongModel):
    # 信息化平台名称
    platform_name = models.CharField(max_length=255, verbose_name='信息化平台名称')
    # 平台用途
    platform_usage = models.TextField(verbose_name='平台用途')
    # 供应商（LT/DX/YD/第三方xx）
    supplier = models.CharField(max_length=255, verbose_name='供应商')
    # 平台费用（元）
    platform_fee = models.DecimalField(max_digits=10, decimal_places=2, verbose_name='平台费用（元）')
    # 到期日期（202X年X月）
    expiration_date = models.DateField(verbose_name='到期日期')
    # 友好三方集成公司（如有填写支撑厂家公司名称，如无填写“无”）
    friendly_integration_company = models.CharField(max_length=255, default='无', verbose_name='友好三方集成公司')
    # 关联集团
    group = models.ForeignKey('GroupCustomerInfo', on_delete=models.DO_NOTHING, db_constraint=False,
                              verbose_name='关联集团信息')

    class Meta:
        managed = False
        db_table = 'information_platform_record'
        verbose_name = '信息化平台记录表'
        verbose_name_plural = verbose_name
        ordering = ('-update_time',)

    def __str__(self):
        return f"{self.platform_name} - 信息化平台记录"


class BusinessOpportunityRecord(CoreModel, SoftDeleteModel, DeptBelongModel):
    # 商机内容
    opportunity_content = models.TextField(verbose_name='商机内容')
    # 商机名称
    name = models.TextField(verbose_name='商机内容')

    # 预算（万元）
    budget = models.DecimalField(max_digits=10, decimal_places=2, verbose_name='预算（万元）')
    # 决策关键人
    decision_maker = models.CharField(max_length=255, verbose_name='决策关键人')
    # 在跟竞争
    competition = models.TextField(verbose_name='在跟竞争')
    # 关联集团
    group = models.ForeignKey('GroupCustomerInfo', on_delete=models.DO_NOTHING, db_constraint=False,
                              verbose_name='关联集团信息')

    class Meta:
        managed = False
        db_table = 'business_opportunity_record'
        verbose_name = '商机管理记录表'
        verbose_name_plural = verbose_name
        ordering = ('-update_time',)

    def __str__(self):
        return f"{self.opportunity_content} - 商机记录"


class ArrearsInformationRecord(CoreModel, DeptBelongModel):
    # 关联集团（必填）
    group = models.ForeignKey(
        'GroupCustomerInfo',
        on_delete=models.DO_NOTHING,
        db_constraint=False,
        verbose_name='关联集团信息'
    )

    # 业务大类（字典值，必填）
    business_category = models.ForeignKey(
        to=Dictionary,
        on_delete=models.PROTECT,  # 防止字典被删除
        limit_choices_to={
            'parent__label': '业务大类',
            'is_value': True,
            'status': True
        },
        verbose_name='业务大类（字典值）',
        related_name='arrears_records',
        null=False,  # ✅ 新增：必填约束
        blank=False  # ✅ 新增：admin界面必填
    )

    # 冗余字段（自动同步）
    business_category_label = models.CharField(
        max_length=100,
        verbose_name='业务大类名称',
        help_text='从字典自动同步的label'
    )
    business_category_value = models.CharField(
        max_length=100,
        verbose_name='业务大类编号',
        help_text='从字典自动同步的value'
    )

    min_billing_period = models.CharField(max_length=255, null=False, default='default', verbose_name='最小账期')
    max_billing_period = models.CharField(max_length=255, null=False, default='default', verbose_name='最大账期')
    arrears_period_count = models.IntegerField(null=False, default=0, verbose_name='欠费账期数')
    total_arrears = models.DecimalField(max_digits=15, decimal_places=2, null=False, default=0.00,
                                        verbose_name='全量欠费（元）')
    stock_arrears = models.DecimalField(max_digits=15, decimal_places=2, null=False, default=0.00,
                                        verbose_name='存量欠费（元）')
    new_arrears = models.DecimalField(max_digits=15, decimal_places=2, null=False, default=0.00, verbose_name='新增欠费（元）')
    current_bad_debt = models.DecimalField(max_digits=15, decimal_places=2, null=False, default=0.00,
                                           verbose_name='当前坏账（元）')

    # ✅ 新增：数据校验
    def clean(self):
        if not self.business_category.is_value:
            raise ValidationError('业务大类必须选择值节点')

    # ✅ 优化：使用信号替代save方法（避免递归调用）
    @classmethod
    def post_save_receiver(cls, sender, instance, **kwargs):
        instance.business_category_label = instance.business_category.label
        instance.business_category_value = instance.business_category.value
        instance.save(update_fields=['business_category_label', 'business_category_value'])

    # ✅ 安全的__str__方法
    def __str__(self):
        return (
            f"{getattr(self.group, 'code', '未知集团')} - "
            f"{self.business_category_label if self.business_category else '未分类'}"
            "欠费记录"
        )

    class Meta:
        managed = False
        db_table = 'arrears_information_record'
        verbose_name = '欠费信息记录表'
        ordering = ('-update_time',)


# ✅ 新增：信号绑定
models.signals.post_save.connect(
    ArrearsInformationRecord.post_save_receiver,
    sender=ArrearsInformationRecord,
    dispatch_uid='update_arrears_business_category'
)


class ImportTask(CoreModel):
    """异步导入任务跟踪模型"""
    STATUS_CHOICES = (
        ('pending', '等待处理'),
        ('processing', '处理中'),
        ('success', '成功'),
        ('failed', '失败'),
        ('canceled', '已取消'),
    )

    # 基础信息 - 只保留一个用户字段
    user = models.ForeignKey(Users, on_delete=models.SET_NULL, null=True, verbose_name='操作人', related_name='import_tasks')
    task_id = models.CharField(max_length=50, unique=True, verbose_name='Celery任务ID')
    file_name = models.CharField(max_length=255, verbose_name='文件名')
    file_size = models.BigIntegerField(verbose_name='文件大小（字节）')
    file_type = models.CharField(max_length=10, verbose_name='文件类型')

    # 业务参数
    clear_before_import = models.BooleanField(default=False, verbose_name='全量导入（清空旧数据）')
    total_records = models.IntegerField(default=0, verbose_name='文件总记录数')

    # 统计信息
    valid_count = models.IntegerField(default=0, verbose_name='有效记录数')
    error_count = models.IntegerField(default=0, verbose_name='错误记录数')
    cleared_count = models.IntegerField(default=0, verbose_name='清空记录数')
    duration_seconds = models.FloatField(default=0, verbose_name='耗时（秒）')

    # 状态与日志
    status = models.CharField(max_length=20, choices=STATUS_CHOICES, default='pending', verbose_name='任务状态')
    error_message = models.TextField(blank=True, null=True, verbose_name='错误详情')
    progress = models.PositiveSmallIntegerField(default=0, verbose_name='进度百分比')

    # 元数据
    ip = models.GenericIPAddressField(blank=True, null=True, verbose_name='操作IP')

    class Meta:
        db_table = 'import_task'
        verbose_name = '导入任务'
        verbose_name_plural = '导入任务'
        indexes = [
            models.Index(fields=['user', '-create_time'], name='idx_user_import'),
            models.Index(fields=['status', 'create_time'], name='idx_import_status'),
        ]

    def update_progress(self, current, total):
        """安全更新进度（避免除零错误）"""
        if total == 0:
            self.progress = 0
        else:
            self.progress = min(int((current / total) * 100), 100)
        self.save(update_fields=['progress'])

    @property
    def duration(self):
        """计算耗时（格式化字符串）"""
        if not self.create_time or not self.update_time:
            return '0s'
        delta = (self.update_time - self.create_time).total_seconds()
        return f'{delta:.2f}s'

    def __str__(self):
        return f'导入任务#{self.id}({self.get_status_display()})'


class OperationLogCelery(models.Model):
    """操作日志模型"""
    ACTION_CHOICES = [
        ('CLEAR_ARREARS_IMPORT', '全量导入前清空数据'),
        ('IMPORT_ARREARS', '导入欠费数据'),
        ('UPDATE_ARREARS', '更新欠费数据'),
        ('DELETE_ARREARS', '删除欠费记录'),
    ]

    user = models.ForeignKey(
        Users,
        on_delete=models.SET_NULL,
        null=True,
        verbose_name='操作用户'
    )
    action = models.CharField(
        max_length=50,
        choices=ACTION_CHOICES,
        verbose_name='操作类型'
    )
    detail = models.TextField(
        verbose_name='操作详情',
        help_text='记录操作的具体信息，如影响行数、错误详情等'
    )
    created_at = models.DateTimeField(
        auto_now_add=True,
        verbose_name='操作时间'
    )

    class Meta:
        db_table = 'operation_log'
        verbose_name = '操作日志'
        verbose_name_plural = verbose_name
        ordering = ['-created_at']

    def __str__(self):
        return f"{self.get_action_display()} - {self.user.username} - {self.created_at.strftime('%Y-%m-%d %H:%M:%S')}"
